package cn.moefly.common.component;

import cn.moefly.common.constants.CommonConstans;
import cn.moefly.common.utils.ThreadPoolUtils;
import cn.moefly.common.utils.YamlUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.Optional;


/**
 * 自动解析yaml并注入线程池
 */
public class YamlThreadPoolRegistrar implements ImportBeanDefinitionRegistrar {

    private final static String YAML_THREAD_POOL_SETTING_PREFIX = "common.threadPoolBean";

    private final static String DEFAULT_POOL_BEAN_NAME_PREFIX = "pool.";


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        final String poolNamePrefix = Optional.ofNullable((String)YamlUtils.readProperties("application.yml", CommonConstans.YAML_KEY_BEAN_NAME_PREFIX)).orElse(DEFAULT_POOL_BEAN_NAME_PREFIX);
        Map<String,Map<String,?>> threadPoolMap = YamlUtils.readProperties("application.yml",YAML_THREAD_POOL_SETTING_PREFIX);

        if (threadPoolMap != null) {
            threadPoolMap.forEach((name, setting) ->
                    registry.registerBeanDefinition(poolNamePrefix + name, new RootBeanDefinition(ThreadPoolTaskExecutor.class,
                            () -> ThreadPoolUtils.ofSettingMap(setting, "pool-" + name + "-"))));

        }
    }

}
